package projet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class JSPFilter
 */
public class JSPFilter implements Filter {

    /**
     * Default constructor. 
     */
    public JSPFilter() {
        // Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest hreq = null;
			HttpServletResponse hresp = null;
			if (request instanceof HttpServletRequest) hreq = (HttpServletRequest) request;
			if (response instanceof HttpServletResponse) hresp = (HttpServletResponse) response;

			// The client requested "/path/somename.jsp", let's redirect them to "/path/somename"
			String jspURI = hreq.getRequestURI();
			String servletURI = jspURI.substring(0, jspURI.lastIndexOf('.'));
			String queryString = hreq.getQueryString();
			if (queryString != null) {
				jspURI += "?"+queryString;
				servletURI += "?"+queryString;
			}
			System.out.println("JSP "+jspURI+" requested! Redirecting to "+servletURI);
			hresp.sendRedirect(servletURI);
			return;
		}
		catch (Throwable e) {
			e.printStackTrace();
		}

		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// Auto-generated method stub
	}

}
